package com.zonesion.robot.ai.wifi.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.zonesion.robot.ai.TheApplication;

import java.lang.reflect.Method;
import java.util.List;

/**
 * Wifi 工具类
 * 封装Wifi的基础操作方法，方便获取Wifi联系信息以及操作Wifi
 */
public class WifiUtils {

    DhcpInfo dhcpInfo;

    private static Context mContext = TheApplication.getInstance();
    //取得WifiManager对象
    private static WifiManager mWifiManager = (WifiManager) mContext
            .getSystemService(Context.WIFI_SERVICE);

    public static enum WifiCipherType {
        WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
    }

    public static boolean isWifiApEnabled(){
        try {
            Method method = mWifiManager.getClass().getMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(mWifiManager);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断是否连接上wifi
     * @return boolean值(isConnect),对应已连接(true)和未连接(false)
     */
    public static boolean isWifiConnect(){
        NetworkInfo mNetworkInfo = ((ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE))
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mNetworkInfo.isConnected();
    }

    /**
     * wifi是否打开
     * @return
     */
    public static boolean isWifiEnabled() {
        return mWifiManager.isWifiEnabled();
    }

    /***
     * 打开wifi
     * */
    public static void OpenWifi() {
        if (!mWifiManager.isWifiEnabled())
            mWifiManager.setWifiEnabled(true);
    }

    /**
     * 关闭wifi
     */
    public static void closeWifi() {
        mWifiManager.setWifiEnabled(false);
    }

    public static boolean connectWifi(String SSID, String Password, WifiCipherType Type){
        if(!isWifiEnabled()) {
            Log.e("TAG","=============wifi是否打开");
            return false;
        }

        // 开启wifi需要一段时间,要等到wifi状态变成WIFI_STATE_ENABLED
        while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING){
            try {
                //避免程序不停循环
                Thread.currentThread();
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        WifiConfiguration wifiConfig = createWifiInfo(SSID, Password, Type);
        if(wifiConfig == null) {
            Log.e("TAG","=============wifiConfigw为空");
            return false;
        }

        WifiConfiguration tempConfig = isExsits(SSID);
        if(tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
            Log.e("TAG","=============tempConfig为空");
        }

        int netID = mWifiManager.addNetwork(wifiConfig);
        Log.e("TAG","============="+netID);
        // 断开连接
        mWifiManager.disconnect();

        // 设置为true,使其他的连接断开
        boolean bRet = mWifiManager.enableNetwork(netID, true);
        Log.e("TAG","=============bRet"+bRet);
        mWifiManager.reconnect();

        return bRet;
    }

    private static WifiConfiguration createWifiInfo(String SSID, String Password,
                                                    WifiCipherType Type){
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();

        config.SSID = "\"" + SSID + "\"";
        if(Type ==  WifiCipherType.WIFICIPHER_NOPASS) {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiCipherType.WIFICIPHER_WEP) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiCipherType.WIFICIPHER_WPA) {

            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

        }else {
            return null;
        }
        return config;
    }

    public static void startScan(){
        mWifiManager.startScan();
    }

    //获取BSSID
    public static String getBSSID() {
        WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
        return mWifiInfo.getBSSID();
    }

    ////获得SSID
    public static String getSSID(){
        WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
        return mWifiInfo.getSSID();
    }


    //获得ip dns
    public static String getWifiIP(){
        if(!mWifiManager.isWifiEnabled()) {
            return null;
        }
        DhcpInfo dhcpInfo = mWifiManager.getDhcpInfo();
        if(dhcpInfo == null) {
            return null;
        }
        //获取32位整型IP地址
        int dns =  dhcpInfo.dns1;
        if (dns == 0)
        {
            return null;
        }
        //把整型地址转换成“*.*.*.*”地址
        String ip=intToIp(dns);
        if (ip == null || ip.startsWith("0"))
        {
            return null;
        }
        return ip;
    }

    private static String intToIp(int i)
    {
        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }

    public static List<ScanResult> getScanResults() {
        return mWifiManager.getScanResults();
    }

    /**
     * 查看以前是否也配置过这个网络
     * @param SSID
     * @return
     */
    private static WifiConfiguration isExsits(String SSID) {
        @SuppressLint("MissingPermission") List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs){
            if(existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }




}
